package com.xsr.controller;

import com.xsr.pojo.User;
import com.xsr.service.UserService;
import com.xsr.service.impl.UserServiceImpl;
import com.xsr.utils.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 邢式瑞
 * @version 1.0
 * @project xiaomi
 * @date 2022/9/13 17:10
 */
@Controller
@RequestMapping("/userservlet")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public String login(String username, String password ,String vcode,HttpSession httpSession) {
        String captcha = (String) httpSession.getAttribute("captcha");
        if (vcode.equalsIgnoreCase(captcha)) {
          User user=  userService.findUserByUsernameAndPwd(username, password);
                System.out.println(captcha);
                httpSession.setAttribute("user",user);
                return "redirect:/index.jsp";


        }
        return null;
    }
    @RequestMapping("/register")
    public  String register(String username,String password,String repassword,String gender, String email){
        System.out.println(password);
        if(!password.equals(repassword)){
            return "redirect:/register.jsp";
        }
        User user = new User(0,username,password,email,gender,0,1, RandomUtils.createCode());
       if(userService.saveUser(user)){
           return"redirect:/registerSuccess.jsp";
       }
       return "redirect:/register.jsp";
    }
    @RequestMapping("/checkName")
    public  String checkName(String username, HttpServletResponse response) throws Exception{
       User user= userService.findByUsername(username);
        if(user!=null){
            response.getWriter().write("1");


        }

        else{
            response.getWriter().write("0");
        }
        return null;
    }
    }

